<?php


namespace App\HttpController;


use App\Cache\UserCache;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;

class Base extends Controller
{
    protected $userinfo;

    protected $nocheck = [
        '/user/login'
    ];
    /**
     * gc 方法将在执行完 afterAction 方法之后自动调用，可自行覆盖实现其他的 gc 回收逻辑
     *
     * CreateTime: 2020/8/19 12:52 上午
     */
    protected function gc()
    {
        parent::gc(); // TODO: Change the autogenerated stub
    }

    /**
     * 当控制器方法执行结束之后将调用该方法，可自行覆盖该方法实现数据回收等逻辑
     *
     * @param string|null $actionName
     * CreateTime: 2020/8/19 12:51 上午
     */
    protected function afterAction(?string $actionName): void
    {
        parent::afterAction($actionName); // TODO: Change the autogenerated stub
    }

    /**
     * 不存在的路由
     * @param string|null $action
     */
    protected function actionNotFound(?string $action)
    {
        $this->writeJson(Status::CODE_NOT_FOUND,null,"非法请求");
    }



    /**
     * 此控制器抛异常时会执行此方法
     *
     * @param \Throwable $throwable
     * @throws \Throwable
     * CreateTime: 2020/8/19 12:48 上午
     */
    protected function onException(\Throwable $throwable): void
    {
        $this->writeJson(STATUS::CODE_BAD_REQUEST,false,$throwable->getMessage());
    }


    /**
     * 所有控制器请求都会先经过该方法，如果此方法返回 false 则请求不继续往下执行，可用于权限验证
     *
     * @param string|null $action
     * @return bool|null
     * CreateTime: 2020/8/19 12:52 上午
     */
    protected function onRequest(?string $action): ?bool
    {
        $uri = $this->request()->getUri()->getPath();

        if(in_array($uri,$this->nocheck)){
            return true;
        }

        $token  = $this->request()->getHeader('token');
        if(empty($token)){
            $this->writeJson(STATUS::CODE_BAD_REQUEST,"无效token");
            return false;
        }

        $userInfo = (new UserCache())->getUserInfoByToken($token);
        if(empty($userInfo)){
            $this->writeJson(STATUS::CODE_BAD_REQUEST,"用户不存在");
            return false;
        }

        $this->userinfo = $userInfo;
        return true;
    }

}